﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;


namespace GameForKids
{
    class DrawGame : GameScreen
    {
        // dinh nghia state  game
        public enum ViewState
        {
            Playing,
            HelpScreen,
            ChartScreen,
            Pause,
            win
        }
        // dinh nghia state hien tai
        public static ViewState viewState;


        // hinh nen
        private Texture2D background;

        //help
        private string helpString = "";
        protected HelpScreen helpScreen;

        // chart
        private ChartScreen chartScreen;

        // pause
        private PauseScreen pauseScreen;

        // win 
        private LevelCompleteScreen levelCompleteScreen;

        //cac button
        protected List<Button> buttons;
        protected Button chartButton;
        protected Button helpButton;
        protected Button musicButton;
        protected Button randButton;
        protected Button nextButton;
        protected Button backButton;

        // cac o chu
        private DrawGameplay gameplay;
        public static int level = 0;
        private SpriteFont numberFont;
        private SpriteFont helpFont;

        // nhac trong game
        private Song gameMusic;
        private SoundEffect buttonSound;
        private SoundEffect buttonPressSound;
        private SoundEffect popupSound;
        private SoundEffect scrollSound;

        private Vector2 locationOfInfo;
        private string textInfo = "";


        // dung cho loading screen
        private SoundEffect timeticksound;

 

        public DrawGame()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0);
        }


        public override void Initialize()
        {
            viewState = ViewState.Playing;
        }

        public override void Activate(bool instancePreserved)
        {
            level = 0;
            locationOfInfo = Vector2.Zero;
            numberFont = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/NumberFont");
            helpFont = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/HelpFont");

            // khoi tao cac button trong game
            buttons = new List<Button>();

            chartButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart_press"),
              ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_chart_press"));
            chartButton.Location = new Point(10, 50);
            chartButton.Clicked += new EventHandler(chartButton_Clicked);

            helpButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help_press"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_help_press"));
            helpButton.Location = new Point(10, 150);
            helpButton.Clicked += new EventHandler(helpButton_Clicked);

            musicButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_on"),
                ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_off"),
                ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/music_off"));
            musicButton.Location = new Point(726, 50);
            musicButton.Clicked += new EventHandler(musicButton_Clicked);
            if (!GameForKids.ISMUSIC)
                musicButton.Hold = true;


            randButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("DrawLetterGame/Images/button_random"),
                ScreenManager.Game.Content.Load<Texture2D>("DrawLetterGame/Images/button_random_press"),
                ScreenManager.Game.Content.Load<Texture2D>("DrawLetterGame/Images/button_random_press"));
            randButton.Location = new Point(726, 150);
            randButton.Clicked += randButton_Clicked;

            backButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre"),
               ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre_press"),
               ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_pre_press"));
            backButton.Location = new Point(10, 400);
            backButton.Clicked += new EventHandler(backButton_Clicked);
            backButton.Disable();

            nextButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next"),
             ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next_press"),
              ScreenManager.Game.Content.Load<Texture2D>("MemoryGame/Images/button_next_press"));
            nextButton.Location = new Point(720, 400);
            nextButton.Clicked += new EventHandler(nextButton_Clicked);

            buttons.Add(chartButton);
            buttons.Add(helpButton);
            buttons.Add(musicButton);
            buttons.Add(randButton);
            buttons.Add(backButton);
            buttons.Add(nextButton);



            chartScreen = new ChartScreen(ScreenManager.Game);
            chartScreen.Clicked += new EventHandler(chartScreen_Clicked);

            // khoi tao cac am thanh
            buttonSound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/buttonPress");
            scrollSound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/sliding");
            buttonPressSound = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/button_click");
            popupSound = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/login_in");
            timeticksound = ScreenManager.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/timetick");

            gameMusic = ScreenManager.Game.Content.Load<Song>("MemoryGame/Sounds/alphabetmusic");
            background = ScreenManager.Game.Content.Load<Texture2D>("DrawLetterGame/Images/background");
            
            if (GameForKids.language == GameForKids.VIET)
            {
                helpString = "CÁCH CHƠI :\n" +
                    "Mục tiêu là phải vẽ theo những số có sẵn.\n" +
                    "Có tất cả 5 màn chơi và độ khó tăng dần, sau\n" +
                    "khi hoàn thành mỗi màn chơi điểm số sẽ được lưu\n" +
                    "lại, bạn có thể mở đồ thị để xem điểm của từng\n" +
                    "                     màn. Điểm số được tính theo\n" +
                    "                     công thức mặc định, bạn cũng\n" +
                    "                     có thể đặt lại công thức bằng\n" +
                    "                     cách chọn vào icon hình máy tính !";
            }
            else
            {
                helpString = "GUIDE :\n" +
                    "The goal must be to draw the number on ex. picture\n" +
                    "There have 5 level and increasing difficulty\n" +
                    "when completion of each level, the score will\n" +
                    "be saved. You can open to see the graph score \n" +
                    "                     of each level .Score is \n" +
                    "                     calculated by default formula\n" +
                    "                     you can set the formula by\n" +
                    "                     select the calculator icon !";
            }

            // khoi tao help screen
            helpScreen = new HelpScreen(ScreenManager.Game, helpString);
            helpScreen.Clicked += new EventHandler(helpScreen_Clicked);

            if (GameForKids.ISMUSIC)
            {
                MediaPlayer.Play(gameMusic);
                MediaPlayer.IsRepeating = true;
            }

            // khoi tao game play
            gameplay = new DrawGameplay(ScreenManager.Game);
            gameplay.startNewLevel(level);

            // khoi tao pause screen
            pauseScreen = new PauseScreen(ScreenManager.Game);
            levelCompleteScreen = new LevelCompleteScreen(ScreenManager.Game);

            base.Activate(instancePreserved);
        }

        // giai phong bo nho
        public override void Unload()
        {
            //  gameplay.unload();
            //  buttons = null;
            base.Unload();
        }


        void randButton_Clicked(object sender, EventArgs e)
        {
            Random rand = new Random();
            level = rand.Next(gameplay.sizeLimit);
            if (level == gameplay.sizeLimit)
            {
                backButton.Enable();
                nextButton.Disable();
   
            }
            else if (level == 0)
            {
                backButton.Disable();
                nextButton.Enable();
            }
            gameplay.startNewLevel(level);
        }




        void chartScreen_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            chartScreen.HideChart();

                    viewState = ViewState.Playing;

        }



        void helpScreen_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            helpScreen.hidehelp();


                    viewState = ViewState.Playing;

        }




        private void nextlevel()
        {
            if (level == gameplay.sizeLimit)
            {
                level = 0;
                gameplay.startNewLevel(level);
                backButton.Disable();
                nextButton.Enable();
            }
            else if (level < gameplay.sizeLimit)
            {
                level++;
                gameplay.startNewLevel(level);
                if (level == gameplay.sizeLimit)
                    nextButton.Disable();
                backButton.Enable();

            }
        }


        void nextButton_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
                buttonSound.Play();
            nextlevel();
        }


        private void backlevel()
        {
            if (level > 0)
            {
                level--;
                gameplay.startNewLevel(level);
            }
            if (level == 0)
                backButton.Disable();
            nextButton.Enable();
        }



        void backButton_Clicked(object sender, EventArgs e)
        {
            if (GameForKids.ISMUSIC)
                buttonSound.Play();
            backlevel();
        }


        void musicButton_Clicked(object sender, EventArgs e)
        {

            if (musicButton.Hold == false)
            {
                musicButton.Hold = true;
                GameForKids.ISMUSIC = false;
                MediaPlayer.Stop();
            }
            else
            {
                musicButton.Hold = false;
                GameForKids.ISMUSIC = true;
                MediaPlayer.Play(gameMusic);
                MediaPlayer.IsRepeating = true;
            }

        }

        void helpButton_Clicked(object sender, EventArgs e)
        {

            if (viewState != ViewState.HelpScreen)
            {
                helpScreen.showhelp();
                viewState = ViewState.HelpScreen;

            }
            else
            {
                helpScreen.hidehelp();

                        viewState = ViewState.Playing;
            }
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
        }

        void chartButton_Clicked(object sender, EventArgs e)
        {

            if (viewState == ViewState.HelpScreen)
                helpScreen.hidehelp();
            chartScreen.ShowChart();
            if (GameForKids.ISMUSIC)
            {
                buttonPressSound.Play();
                scrollSound.Play();
            }
            viewState = ViewState.ChartScreen;
        }






        public override void Update(Microsoft.Xna.Framework.GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            TouchPanel.EnabledGestures = GestureType.FreeDrag;
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            if (gameplay.iswin)
            {

                if (viewState != ViewState.win)
                {
                    int _diem = gameplay.getScore();
                    levelCompleteScreen.diem = _diem;
                    levelCompleteScreen.showScreen();
                    viewState = ViewState.win;
                    gameplay.saveScore(_diem);

                }
                levelCompleteScreen.Update(gameTime);
            }

            // bat su kien phim khi pause
            if (PauseClickState.clickstate == PauseClickState.ClickState.menu)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                GoMenu();
            }
            else if (PauseClickState.clickstate == PauseClickState.ClickState.resume)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                Resume();
            }
            else if (PauseClickState.clickstate == PauseClickState.ClickState.replay)
            {
                PauseClickState.clickstate = PauseClickState.ClickState.none;
                Replay();
            }

            // bat su kien phim khi win
            if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.menu)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                GoMenu();
            }
            else if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.replay)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                Replay();
            }
            else if (LevelCompleteClickState.clickstate == LevelCompleteClickState.ClickState.next)
            {
                LevelCompleteClickState.clickstate = LevelCompleteClickState.ClickState.none;
                Next();
            }

            gameplay.Update(gameTime);

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }




        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spritebatch = ScreenManager.SpriteBatch;
            spritebatch.Begin();
            spritebatch.Draw(background, new Vector2(0, 0), Color.White);

            foreach (Button button in buttons)
            {
                button.Draw(spritebatch);
            }



            textInfo = "";
            if (GameForKids.language == GameForKids.ANH)
            {
                textInfo += "DrawNumber   --   " + "Name: " + GameForKids.userName;
            }
            else
            {
                textInfo += "Tập viết số  --   " +  "Tên: " + GameForKids.userName;
               
            }
            locationOfInfo.X = (GameForKids.WIDTH - helpFont.MeasureString(textInfo).X) / 2;
            locationOfInfo.Y = 445;

                spritebatch.DrawString(helpFont,
                    textInfo,
                    locationOfInfo,
                    Color.White);


                gameplay.Draw(gameTime, spritebatch);

   
            helpScreen.Draw(spritebatch);
            chartScreen.Draw(spritebatch);
            pauseScreen.Draw(spritebatch);
            levelCompleteScreen.Draw(spritebatch);

            /*
            var appCurrentMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            var appPeakMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
            spritebatch.DrawString(helpFont, "Current RAM: " + appCurrentMemoryUsage.ToString(), new Vector2(10, 10), Color.White);
            spritebatch.DrawString(helpFont, "Total RAM: " + appPeakMemoryUsage.ToString(), new Vector2(10, 30), Color.White);
            */

            spritebatch.End();
        }

        public void Next()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            viewState = ViewState.Playing;
            nextlevel();

        }

        public void Resume()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();

                viewState = ViewState.Playing;
        }

        public void Replay()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();

            viewState = ViewState.Playing;

            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            gameplay.RestartLevel();
        }

        public void GoMenu()
        {

            if (chartScreen.show)
                chartScreen.HideChart();
            if (helpScreen.show)
                helpScreen.hidehelp();
            if (pauseScreen.show)
                pauseScreen.hidePause();


            if (levelCompleteScreen.show)
                levelCompleteScreen.hideScreen();
            GameForKids.gameState = GameState.MainMenu;
            ExitScreen();
            if (GameForKids.ISMUSIC)
            {
                gameMusic = ScreenManager.Game.Content.Load<Song>("MainMenu/Sounds/music_of_main_menu");
                MediaPlayer.IsRepeating = true;
                MediaPlayer.Play(gameMusic);
            }
            MainMenuScreen.viewState = VIEWSTATE.effectIN;
        }


        public override void HandleInput(Microsoft.Xna.Framework.GameTime gameTime, InputState input)
        {

            
            PlayerIndex player;
            if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player) && viewState != ViewState.win)
            {
             if (viewState != ViewState.Pause)
                {
                    if (viewState == ViewState.ChartScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        chartScreen.HideChart();
  
                            viewState = ViewState.Playing;
                    }
                    else if (viewState == ViewState.HelpScreen)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            scrollSound.Play();
                        }
                        helpScreen.hidehelp();
      
                            viewState = ViewState.Playing;
                    }
                    else
                    {
                        if (GameForKids.ISMUSIC)
                            popupSound.Play();
                        pauseScreen.showPause();
                        viewState = ViewState.Pause;
                    }
                }
                else if (viewState == ViewState.Pause)
                {
                    pauseScreen.hidePause();
                    if (helpScreen.show)
                        helpScreen.hidehelp();
                    if (chartScreen.show)
                        chartScreen.HideChart();
         
                        viewState = ViewState.Playing;
                }
            }

            TouchCollection touches = input.TouchState;
            if (touches.Count > 0)
            {
                TouchLocation touch = touches[0];
                {
                    switch (viewState)
                    {
                        case ViewState.Playing:
                            {
                                gameplay.TouchEvent(input);
                                foreach (Button button in buttons)
                                {
                                    button.TouchEvent(touch);
                                }
                            }; break;

                        case ViewState.Pause:
                            {
                                pauseScreen.TouchEvent(touch);
                            }
                            break;

                        case ViewState.HelpScreen:
                            {
                                helpScreen.TouchEvent(touch);
                                helpButton.TouchEvent(touch);
                                chartButton.TouchEvent(touch);
                                musicButton.TouchEvent(touch);
                                randButton.TouchEvent(touch);

                            }; break;
                        case ViewState.ChartScreen:
                            {
                                chartScreen.TouchEvent(touch);
                                musicButton.TouchEvent(touch);
                                randButton.TouchEvent(touch);

                            }; break;
                        case ViewState.win:
                            {
                                levelCompleteScreen.TouchEvent(touch);

                            }; break;
                    }
                }
            }
        }
    }
}
